package com.hcy.driverapi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @Author huchenying
 * @Description: 更细粒度的权限拦截 可在这里做进一步校验 方法上添加 @PreAuthorize("hasPermission('admin2','admin2')") 即可
 * @Date 2021/11/23 19:07
 */

@Component
@Configuration
public class CustomPermissionEvaluator implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {

        //获取当前用户
//        User user = (User) authentication.getPrincipal();
        //获取当前用户权限
//        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        GrantedAuthority pm = new SimpleGrantedAuthority((String) permission);
        return authentication.getAuthorities().contains(pm);
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }

    //把自定义的加入
    @Bean
    public DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler(){
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(new CustomPermissionEvaluator());
        return handler;
    }
}
